import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.naming.Context;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.w3c.dom.Text;

public class AdvancedIPCount {

    // 自定义计数器枚举
    public static enum LogCounter {
        VALID, INVALID, MALFORMED
    }

    // Mapper 类：提取 IP 地址并输出 (IP, 1) 键值对
    public static class IPMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text ip = new Text();
        
        // 可配置的 IP 提取模式
        private Pattern ipPattern;
        private int ipGroupIndex = 1; // 默认 IP 在第一个捕获组
        
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            Configuration conf = context.getConfiguration();
            
            // 从配置中获取 IP 提取模式和组索引
            String patternStr = conf.get("ip.pattern", "^(\\d+\\.\\d+\\.\\d+\\.\\d+)");
            ipPattern = Pattern.compile(patternStr);
            
            ipGroupIndex = conf.getInt("ip.group.index", 1);
        }

        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            
            try {
                Matcher matcher = ipPattern.matcher(line);
                
                if (matcher.find()) {
                    // 提取 IP 地址
                    String ipAddress = matcher.group(ipGroupIndex);
                    ip.set(ipAddress);
                    context.write(ip, one);
                    context.getCounter(LogCounter.VALID).increment(1);
                } else {
                    // 无法匹配 IP 地址
                    context.getCounter(LogCounter.INVALID).increment(1);
                }
            } catch (Exception e) {
                // 处理解析异常
                context.getCounter(LogCounter.MALFORMED).increment(1);
            }
        }
    }

    // Combiner 类：在 Map 阶段进行本地聚合，减少网络传输
    public static class IPCombiner extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context) 
                throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    // Reducer 类：对相同 IP 的访问次数进行累加
    public static class IPReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();
        
        // 可配置的阈值，只输出访问次数超过阈值的 IP
        private int threshold = 0;

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            Configuration conf = context.getConfiguration();
            threshold = conf.getInt("ip.threshold", 0);
        }

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context) 
                throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            
            // 只输出超过阈值的 IP
            if (sum >= threshold) {
                result.set(sum);
                context.write(key, result);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        
        if (otherArgs.length < 2) {
            System.err.println("Usage: AdvancedIPCount <input> <output> [ip.pattern] [ip.group.index] [ip.threshold]");
            System.exit(2);
        }

        // 设置可配置参数
        if (otherArgs.length > 2) {
            conf.set("ip.pattern", otherArgs[2]);
        }
        
        if (otherArgs.length > 3) {
            conf.setInt("ip.group.index", Integer.parseInt(otherArgs[3]));
        }
        
        if (otherArgs.length > 4) {
            conf.setInt("ip.threshold", Integer.parseInt(otherArgs[4]));
        }

        Job job = Job.getInstance(conf, "Advanced IP Count");
        job.setJarByClass(AdvancedIPCount.class);
        
        // 设置 Mapper、Combiner 和 Reducer
        job.setMapperClass(IPMapper.class);
        job.setCombinerClass(IPCombiner.class);
        job.setReducerClass(IPReducer.class);
        
        // 设置输出键值对类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        
        // 设置输入输出路径
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        
        // 提交作业并等待完成
        boolean success = job.waitForCompletion(true);
        
        // 输出统计信息
        if (success) {
            System.out.println("Valid log entries: " + job.getCounters().findCounter(LogCounter.VALID).getValue());
            System.out.println("Invalid log entries: " + job.getCounters().findCounter(LogCounter.INVALID).getValue());
            System.out.println("Malformed log entries: " + job.getCounters().findCounter(LogCounter.MALFORMED).getValue());
        }
        
        System.exit(success ? 0 : 1);
    }
} 